package com.ujiuye.controller;

import com.ujiuye.context.BaseContext;
import com.ujiuye.domain.po.User;
import com.ujiuye.exceptions.MyException;
import com.ujiuye.service.IUserService;
import com.ujiuye.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("user")
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private JwtUtils jwtUtils;

    @PostMapping("/register")
    public String register(@RequestBody User user) {
        userService.save(user);
        return "注册成功!";
    }

    @PostMapping("/login")
    public String login(@RequestBody User user, HttpServletRequest request,
                        HttpServletResponse response) {

        List<User> list = userService.findUser(user);
        if (list == null || list.isEmpty()) {
            MyException.error("登录失败");
        }
        /* Map<String, Object> resultMap = new HashMap<>();*/
        // 表示系统中有这样的用户
        // 得到用户
        user = list.get(0);
        BaseContext.setCurrentId(String.valueOf(user.getUid()));

        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("companyId", "010");
        dataMap.put("companyName", "ujiuye");
        //生成token并存入数据返回
        String token = jwtUtils.createJwt(user.getUid() + "", user.getName(),
                dataMap);
        if (token == null) {
            MyException.error("token令牌生成失败");
        }
        return token;
    }
}
